package com.candy.service.impl;

import com.candy.bean.LoginUser;
import com.candy.bean.User;
import com.candy.service.LoginService;
import com.candy.utils.JwtUtil;
import com.candy.utils.RedisCache;
import com.candy.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //    AuthenticationManager的authenticate方法来进行用户认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)) {
            throw new RuntimeException("用户不存在");
        }
//        通过authenticate获取用户的信息
        LoginUser loginUser=(LoginUser) authenticate.getPrincipal();
//        获取用户的ID
        String userid = loginUser.getUser().getId().toString();
//        根据用户的id进行生成token
        String jwt = JwtUtil.createJWT(userid);
//        将数据保存在map中返回前端
        Map<String,String> token=new HashMap<>();
        token.put("token",jwt);
//        将信息存储在redis里面
        redisCache.setCacheObject("login"+userid,loginUser);
        return new ResponseResult<>(200,"登录成功",token);
    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        //删除redis中的信息
        redisCache.deleteObject("login"+userId);
        return new ResponseResult(200,"注销成功");
    }
}
